package com.fypg.module.blooddonation.api.client.service.dictionary;

import com.fypg.framework.common.util.json.JsonUtils;
import com.fypg.module.blooddonation.api.client.dal.bloodPlatform.DictDownloadReq;
import com.fypg.module.blooddonation.api.client.dal.bloodPlatform.DictDownloadResp;
import com.fypg.module.blooddonation.api.client.dal.bloodStation.BaseResponse;
import com.fypg.module.blooddonation.api.client.enums.ApiPathConstants;
import com.fypg.module.blooddonation.api.client.enums.BloodConstants;
import com.fypg.module.blooddonation.api.client.enums.DictConstants;
import com.fypg.module.blooddonation.api.client.enums.ErrorCodeConstants;
import com.fypg.module.blooddonation.api.client.utils.Sm4KeyUtil;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

import static com.fypg.framework.common.exception.util.ServiceExceptionUtil.exception;

@Service
@RequiredArgsConstructor
@Slf4j
public class DictionaryServiceImpl implements  DictionaryService {

    private final WebClient webClient;
    private final Sm4KeyUtil sm4KeyUtil;

    @Value("${blood.platform.url")
    private String baseUrl;
    @Value("${blood.platform.system-key:1}")
    private String systemKey;

    /**
     * 下载字典（带缓存）
     *
     * @param dictionaryKey 字典键
     * @param orgUuid 机构UUID
     * @return 字典响应
     * @ 当接口调用失败时抛出异常
     */
    @Cacheable(
            value = "blood_platform_dict",
            key = "'dict:' + #dictionaryKey + ':org:' + #orgUuid"
    )
    @Override
    public DictDownloadResp downloadDictionary(String dictionaryKey, String orgUuid)  {
        if (StringUtils.isEmpty(dictionaryKey)) {
            throw exception(ErrorCodeConstants.BLOOD_PARAM_VALIDATION_FAILED, "dictionaryKey不能为空");
        }
        if (StringUtils.isEmpty(orgUuid)) {
            throw exception(ErrorCodeConstants.BLOOD_PARAM_VALIDATION_FAILED, "orgUuid不能为空");
        }

        // 构造请求
        DictDownloadReq request = new DictDownloadReq();
        request.setSystemKey(systemKey);
        request.setUuid(orgUuid);
        request.setDictionaryKey(dictionaryKey);

        String url = baseUrl + ApiPathConstants.BloodPlatform.DICTIONARY_DOWNLOAD;

        String requestBody = JsonUtils.toJsonString(request);

        BaseResponse<DictDownloadResp> response = webClient.post()
                .uri(url)
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(new ParameterizedTypeReference<BaseResponse<DictDownloadResp>>() {})
                .block();

        if (response != null && response.isHttpSuccess()) {
            DictDownloadResp dictDownloadResp = response.getDecryptedData(DictDownloadResp.class, sm4KeyUtil.getSm4Key());
            if (dictDownloadResp != null && BloodConstants.NORMAL_RESULT_CODE.equals(dictDownloadResp.getResultCode())) {
                return dictDownloadResp;
            } else {
                String errorMsg = dictDownloadResp != null ? dictDownloadResp.getErrMsg() : "业务响应为空";
                throw exception(ErrorCodeConstants.BLOOD_DICTIONARY_QUERY_FAILED, errorMsg);
            }
        } else {
            String responseCode = response != null ? response.getResponseCode() : "无响应";
            throw exception(ErrorCodeConstants.BLOOD_HTTP_REQUEST_FAILED, "响应码: " + responseCode);
        }
    }

    /**
     * 获取证件类型字典
     *
     * @param orgUuid 机构UUID
     * @return 字典响应
     * @ 当接口调用失败时抛出异常
     */
    public DictDownloadResp getIdentityTypeDict(String orgUuid)  {
        return downloadDictionary(DictConstants.IDENTITY_TYPE, orgUuid);
    }

    /**
     * 获取检测总结论字典
     *
     * @param orgUuid 机构UUID
     * @return 字典响应
     * @ 当接口调用失败时抛出异常
     */
    public DictDownloadResp getTestFinalResultDict(String orgUuid)  {
        return downloadDictionary(DictConstants.TEST_FINAL_RESULT, orgUuid);
    }

    /**
     * 获取教育程度字典
     *
     * @param orgUuid 机构UUID
     * @return 字典响应
     * @ 当接口调用失败时抛出异常
     */
    public DictDownloadResp getEducationDict(String orgUuid)  {
        return downloadDictionary(DictConstants.EDUCATION, orgUuid);
    }

    /**
     * 清理字典缓存
     *
     * @param dictionaryKey 字典键
     */
    @CacheEvict(value = "blood_platform_dict", key = "'dict:' + #dictionaryKey + ':org:' + #orgUuid")
    @Override
    public void clearDictCache(String dictionaryKey, String orgUuid) {

    }

    /**
     * 清理所有字典缓存
     */
    @CacheEvict(value = "blood_platform_dict", allEntries = true)
    @Override
    public void clearAllDictCache() {
    }





}
